package edu.tjpu.share.service;

import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.newui.MainTabHost;
import edu.tjpu.share.po.FileForUpload;
import edu.tjpu.share.task.UploadTask;

public class UploadService extends Service {

	public final static int UPDATE_UPLOAD = 4;
	public final static int START_UPLOAD = 3;
	public final static int UPLOAD_COMPLETE = 1;
	public final static int NOTIFY_COMPLETE = 2;
	public final static int UPLOAD_FAILED = 0;
	private NotificationManager nm;
	private SparseArray<Notification> nArray;
	private SparseArray<PendingIntent> ptArray;
	private SparseArray<Intent> iArray;
	//private List<Integer> notificationIDList;
	private CountDownLatch runningThreadNum = null;
	private Intent mIntentToStop;

	final static private String TAG = "UploadService";
	final static public String UPLOAD_ACTION = "edu.tjpu.share.UploadService";

	// private BroadcastReceiver connChagRec = new ConnectionChangeReceiver();
	private UploadBinder mBinder = new UploadBinder();

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	@Override
	public void onCreate() {
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nArray = new SparseArray<Notification>();
		ptArray = new SparseArray<PendingIntent>();
		iArray = new SparseArray<Intent>();
		//notificationIDList = new ArrayList<Integer>();
		mIntentToStop = new Intent();
		mIntentToStop.setAction(UploadService.UPLOAD_ACTION);
		mIntentToStop.setClass(UploadService.this, UploadService.class);
		super.onCreate();
	}

	@Override
	public int onStartCommand(final Intent intent, int flags, final int startId) {
		if (intent != null) {
			if (runningThreadNum == null) {
				runningThreadNum = new CountDownLatch(intent.getIntExtra(
						"runningThreadNum", 1));
			}
			UploadThread uploadThread = new UploadThread(intent, startId,
					mStopServiceHandler);
			uploadThread.start();
			return START_STICKY;
		}
		return super.onStartCommand(intent, flags, startId);

	}

	// 子线程
	public class UploadThread extends Thread {

		// 子线程记数器,记载着运行的线程数
		private Intent intent;
		private int startId;
		private Handler mStopServiceHandler;
		private Thread runThread = null;

		public UploadThread(Intent intent, int startId,
				Handler mStopServiceHandler) {
			this.intent = intent;
			this.startId = startId;
			this.mStopServiceHandler = mStopServiceHandler;
		}

		@Override
		public void run() {
			runThread = currentThread();
			Log.d(TAG, "New Thread Started" + Thread.currentThread().getName());
			int notification_id = new Random(System.currentTimeMillis()).nextInt();
			//notificationIDList.add(notification_id);
			Log.w(TAG, "UploadService get new  notification_id:"
					+ notification_id);
			Bundle bundle = intent.getExtras();
			HashMap<String, Object> map = (HashMap<String, Object>) bundle
					.getSerializable("values");
			Log.i(TAG, "UploadService Received start id " + startId + ": "
					+ intent);
			upload(map, notification_id, mUploadThreadHandler);
		}

		private Handler mUploadThreadHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case UploadService.UPLOAD_COMPLETE:
					mStopServiceHandler.sendEmptyMessage(UploadService.UPLOAD_COMPLETE);
					if (runThread != null) {
						runThread.interrupt();
					}
					break;
				case UploadService.UPLOAD_FAILED:
					if (runThread != null) {
						runThread.interrupt();
					}
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
	}

	private Handler mStopServiceHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UploadService.UPLOAD_COMPLETE:

				runningThreadNum.countDown();
				if (runningThreadNum.getCount() == 0) {
					UploadService.this.stopService(mIntentToStop);
				}

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void onStart(Intent intent, int startId) {
		/*
		 * Bundle bundle = intent.getExtras(); map = (HashMap<String, Object>)
		 * bundle.getSerializable("values"); Log.i(TAG,
		 * "UploadService Received start id " + startId + ": " + intent);
		 * FileForUpload file = (FileForUpload) map.get(Fields.FILE_FORUPLOAD);
		 * Toast.makeText(this, "已启动后台服务上传:" + file.getFname(),
		 * Toast.LENGTH_LONG) .show(); upload();
		 */
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		/*
		 * Iterator<Integer> iterator = notificationIDList.iterator(); while
		 * (iterator.hasNext()) { int notificationID = iterator.next();
		 * nm.cancel(notificationID); }
		 */
		super.onDestroy();
	}

	@SuppressWarnings("unchecked")
	public void upload(HashMap<String, Object> map, int notification_id,
			Handler mUploadThreadHandler) {
		FileForUpload file = (FileForUpload) map.get(Fields.FILE_FORUPLOAD);
		String fileName = file.getFname();
		if (fileName.length() > 9) {
			fileName = fileName.substring(0, 9)
					+ "..."
					+ fileName.substring(fileName.length() - 4,
							fileName.length());
		}
		Log.i(TAG, "UploadService start uploading " + fileName);

		Message msg = new Message();
		Bundle bundle = new Bundle();
		bundle.putString("fileName", fileName);
		bundle.putInt("notification_id", notification_id);
		msg.what = UploadService.START_UPLOAD;
		msg.setData(bundle);
		uploadHandler.sendMessage(msg);

		map.put("mUploadThreadHandler", mUploadThreadHandler);
		map.put("uploadHandler", uploadHandler);
		map.put("notification_id", notification_id);
		new UploadTask().execute(map);
	}

	private Handler uploadHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			String fileName = bundle.getString("fileName");

			Notification n;
			PendingIntent pt;
			Intent i;

			switch (msg.what) {
			case UploadService.UPDATE_UPLOAD:
				n = nArray.get(bundle.getInt("notification_id"));
				n.setLatestEventInfo(UploadService.this, "正在上传:" + fileName,
						bundle.getInt("uploadPercent") + "%",
						ptArray.get(bundle.getInt("notification_id")));
				nm.notify(bundle.getInt("notification_id"), n);
				break;
			case UploadService.START_UPLOAD:
				Toast.makeText(UploadService.this, "已启动后台服务上传:" + fileName,
						Toast.LENGTH_LONG).show();
				n = new Notification(R.drawable.uploading, "正在上传:" + fileName,
						System.currentTimeMillis());
				i = new Intent(UploadService.this, MainTabHost.class);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				iArray.put(bundle.getInt("notification_id"), i);
				pt = PendingIntent.getActivity(UploadService.this, 0, i, 0);
				ptArray.put(bundle.getInt("notification_id"), pt);
				// 点击通知后的动作，这里是转回main 这个Acticity
				n.setLatestEventInfo(UploadService.this, "Share-正在上传:"
						+ fileName, "0%", pt);
				nArray.put(bundle.getInt("notification_id"), n);
				// 发出通知
				nm.notify(bundle.getInt("notification_id"), n);
				break;
			case UploadService.UPLOAD_COMPLETE:
				n = nArray.get(bundle.getInt("notification_id"));
				pt = ptArray.get(bundle.getInt("notification_id"));
				n.defaults = Notification.DEFAULT_SOUND;// 铃声提醒
				n.setLatestEventInfo(UploadService.this, "Share", fileName
						+ "上传完成。", pt);
				nm.notify(bundle.getInt("notification_id"), n);
				Toast.makeText(UploadService.this,
						"Share-" + fileName + "上传成功！", Toast.LENGTH_SHORT)
						.show();
				// 停止服务
				// stopService(i);
				break;
			case UploadService.NOTIFY_COMPLETE:
				n = nArray.get(bundle.getInt("notification_id"));
				pt = ptArray.get(bundle.getInt("notification_id"));
				n.defaults = Notification.DEFAULT_SOUND;// 铃声提醒
				n.setLatestEventInfo(UploadService.this, "Share", fileName
						+ "上传完成。", pt);
				nm.notify(bundle.getInt("notification_id"), n);
				Toast.makeText(UploadService.this,
						"Share-" + fileName + "上传成功！", Toast.LENGTH_SHORT)
						.show();
				// 停止服务
				// stopService(i);
				break;
			case UploadService.UPLOAD_FAILED:
				n = nArray.get(bundle.getInt("notification_id"));
				pt = ptArray.get(bundle.getInt("notification_id"));
				n.setLatestEventInfo(UploadService.this, "Share", fileName
						+ "上传失败!", pt);
				nm.notify(bundle.getInt("notification_id"), n);
				Toast.makeText(UploadService.this,
						"Share-" + fileName + "上传失败！", Toast.LENGTH_SHORT)
						.show();
				// stopService(i);
				break;
			case Fields.NETWORK_CONNECTION_ERROR:
				n = nArray.get(bundle.getInt("notification_id"));
				pt = ptArray.get(bundle.getInt("notification_id"));
				n.setLatestEventInfo(UploadService.this, "网络错误！", fileName
						+ "上传失败!", pt);
				nm.notify(bundle.getInt("notification_id"), n);
				Toast.makeText(UploadService.this,
						"网络错误！-" + fileName + "上传失败！", Toast.LENGTH_SHORT)
						.show();
				// stopService(i);
				break;
			default:
				// stopService(i);
			}
		}
	};

	public class UploadBinder extends Binder {
		public UploadService getService() {
			return UploadService.this;
		}
	}
}
